package com.fsd.core.filter;

import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.ModelAndView;
import com.fsd.core.bean.ExceptionInfo;
import com.fsd.core.util.FilterUtil;
import net.sf.json.JSONObject;

/** 
 * 防止SQL注入的拦截器
 * 
 * @author lumingbao
 */
public class SQLInjectInterceptor implements HandlerInterceptor{

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		// TODO Auto-generated method stub
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = null;
		Enumeration<String> names = request.getParameterNames();
 		while (names.hasMoreElements()) { 
 			String name = names.nextElement(); 
 			String[] values = request.getParameterValues(name);
  			for (String value : values) {
  				value = URLDecoder.decode(value.replaceAll("%", "%25"), "utf-8");
  				try {
  					FilterUtil.checkSql(value);
				} catch (Exception e) {
					// TODO: handle exception
					String path = request.getContextPath();
					String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
					response.sendRedirect(basePath + "index.html");
					return false;
				}
			}
		}
 		
 		Map<String, String> map = (Map) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
 		if(map != null) {
 			for(Map.Entry<String, String> entry: map.entrySet()) {
 				String value = entry.getValue();
 				value = URLDecoder.decode(value.replaceAll("%", "%25"), "utf-8");
 				try {
  					FilterUtil.checkSql(value);
				} catch (Exception e) {
					// TODO: handle exception
					String path = request.getContextPath();
					String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
					response.sendRedirect(basePath + "index.html");
					return false;
				}
 	 		}
 		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		// TODO Auto-generated method stub
		
	}
}